package com.ruoyi.common.utils;

import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 校验器工具类
 */
public abstract class ValidatorUtils {

    public static final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    public static <T> BindingResult validate(T entity, Class<?>... groups) {
        BindingResult br = new BeanPropertyBindingResult(entity, entity.getClass().getName());
        Set<ConstraintViolation<T>> res = validator.validate(entity, groups);
        res.forEach(r -> br.addError(new ObjectError(r.getPropertyPath().toString(), r.getMessage())));
        return br;
    }

    public static <T> BindingResult validate(T entity) {
        return validate(entity, Default.class);
    }

    public static String errs(BindingResult br) {
        if (null == br || !br.hasErrors()) {
            return null;
        }
        return br.getAllErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining(";"));
    }

    public static <T> String errs(T entity, Class<?>... groups) {
        return errs(validate(entity, groups));
    }

    public static <T> String errs(T entity) {
        return errs(entity, Default.class);
    }

    public interface A {}
    public interface B {}
    public interface C {}
    public interface D {}
    public interface E {}
    public interface F {}
    public interface G {}
    public interface H {}
}
